package com.h3c.nem.service.impl;

import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.eos.common.util.IdWorker;
import com.h3c.nem.cache.TbOfferWorkerCache;
import com.h3c.nem.dto.FamilyAndContactorDTO;
import com.h3c.nem.entity.TbOfferContactor;
import com.h3c.nem.entity.TbOfferFamily;
import com.h3c.nem.entity.TbOfferWorker;
import com.h3c.nem.mapper.TbOfferFamilyMapper;
import com.h3c.nem.mapper.TbOfferWorkerMapper;
import com.h3c.nem.mapstruct.TbOfferContactorMapstruct;
import com.h3c.nem.mapstruct.TbOfferFamilyMapstruct;
import com.h3c.nem.sap.RfcManager;
import com.h3c.nem.service.ITbOfferContactorService;
import com.h3c.nem.service.ITbOfferFamilyService;
import com.h3c.nem.utils.CommonUtil;
import com.h3c.nem.vo.TbOfferFamilyVO;
import com.sap.conn.jco.JCoDestination;
import com.sap.conn.jco.JCoFunction;
import com.sap.conn.jco.JCoParameterList;
import com.sap.conn.jco.JCoStructure;
import lombok.AllArgsConstructor;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.Objects;

/**
 * 家庭成员实现类
 *
 * @author chenyifan
 * @since 2022-06-02 17:50:02
 */
@Service
@AllArgsConstructor
@Slf4j
public class TbOfferFamilyServiceImpl extends ServiceImpl<TbOfferFamilyMapper, TbOfferFamily> implements ITbOfferFamilyService {

    private final ITbOfferContactorService contactorService;
    private final TbOfferWorkerMapper tbOfferWorkerMapper;
    @Resource
    private RfcManager rfcManager;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveFamilyInfo(FamilyAndContactorDTO familyAndContactorDTO) {
        if(Objects.nonNull(familyAndContactorDTO.getFamilyDTOS()) && familyAndContactorDTO.getFamilyDTOS().size()>0){
            remove(new QueryWrapper<TbOfferFamily>().lambda()
                    .eq(TbOfferFamily::getWorkerId,CommonUtil.getActivUser().getUserId())
            );
            List<TbOfferFamily> offerFamilies = TbOfferFamilyMapstruct.INSTANCE.DTOList2EntityList(familyAndContactorDTO.getFamilyDTOS());
            offerFamilies.forEach(s->s.setFamilyId(IdWorker.nextId()+"")
                    .setUpdateTime(new Date())
                    .setWorkerId(CommonUtil.getActivUser().getUserId()));
            saveBatch(offerFamilies);
            TbOfferWorkerCache.updateFillStatus(CommonUtil.getActivUser().getUserId(),TbOfferWorkerCache.FAMILY);
        }
        if(Objects.nonNull(familyAndContactorDTO.getContactorDTOS()) && familyAndContactorDTO.getContactorDTOS().size()>0){
            contactorService.remove(new QueryWrapper<TbOfferContactor>().lambda()
                    .eq(TbOfferContactor::getWorkerId,CommonUtil.getActivUser().getUserId())
            );
            List<TbOfferContactor> tbOfferContactors = TbOfferContactorMapstruct.INSTANCE.DTOList2EntityList(familyAndContactorDTO.getContactorDTOS());
            tbOfferContactors.forEach(s->s.setContactorId(IdWorker.nextId()+"")
                    .setUpdateTime(new Date())
                    .setWorkerId(CommonUtil.getActivUser().getUserId()));
            contactorService.saveBatch(tbOfferContactors);
            TbOfferWorkerCache.updateFillStatus(CommonUtil.getActivUser().getUserId(),TbOfferWorkerCache.CONTACTOR);
        }
    }

    @Override
    public List<TbOfferFamilyVO> showFamilyInfo() {
        List<TbOfferFamily> offerFamilies = list(new QueryWrapper<TbOfferFamily>().lambda()
                .eq(TbOfferFamily::getWorkerId, CommonUtil.getActivUser().getUserId())
        );
        return TbOfferFamilyMapstruct.INSTANCE.entityList2VoList(offerFamilies);
    }

    @Override
    public List<TbOfferFamilyVO> getFamilyByWorkerId(String workerId) {
        QueryWrapper<TbOfferFamily> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(TbOfferFamily::getWorkerId, workerId);
        return TbOfferFamilyMapstruct.INSTANCE.entityList2VoList(list(queryWrapper));
    }
    public String relationFormat(String oriRela) {
        switch (oriRela) {
            case "丈夫":
                return "01";
            case "妻子":
                return "02";
            case "父亲":
                return "05";
            case "母亲":
                return "06";
            case "姐姐":
                return "11";
            case "妹妹":
                return "12";
            case "哥哥":
                return "13";
            case "弟弟":
                return "14";
            default:
                return "";
        }
    }
    public void fixFamily(List<String> workerId) {
        workerId.forEach(id -> {
            TbOfferWorker offerWorker = tbOfferWorkerMapper.selectById(id);
            List<TbOfferFamily> list = lambdaQuery().eq(TbOfferFamily::getWorkerId, id).list();
            String yyyyMMdd = DateUtil.format(offerWorker.getContractBeginDate(), "yyyyMMdd");
            list.forEach(f -> {
                String relationType = f.getRelationType();
                String format = relationFormat(relationType);
                if (!StringUtils.isEmpty(format)) {
                    f.setRelationType(format);
                    boolean success = callSapForAddFamily(f, yyyyMMdd, offerWorker.getRegularWorkerId());
                    if (success) {
                        LambdaUpdateWrapper<TbOfferFamily> familyWrapper = new LambdaUpdateWrapper<>();
                        familyWrapper.set(TbOfferFamily::getRelationType, format)
                                        .eq(TbOfferFamily::getFamilyId, f.getFamilyId());
                        update(familyWrapper);
                    }
                }
            });
        });
    }

    @SneakyThrows
    public boolean callSapForAddFamily(TbOfferFamily family, String beginDate, String regularId) {

        //获取SAP客户端
        rfcManager.connect();
        JCoDestination destination = rfcManager.getDestination();
        //调用SAP接口
        JCoFunction func = rfcManager.getFunction(destination, "Z_BAPI_FAMILY_CREATE");
        //组装SAP入参
        JCoStructure data = func.getImportParameterList().getStructure("BAPI_FAMILY_DATA_IMPORT");
        log.info("更新家庭成员SAP 入参======");
        data.setValue("BEGDA", beginDate);
        log.info("BEGDA开始日期={}", beginDate);
        data.setValue("ENDDA", "99991231");
        data.setValue("PERNR", regularId);
        log.info("PERNR员工编号={}", regularId);
        data.setValue("FAMSA", family.getRelationType());
        log.info("FAMSA亲属关系={}",family.getRelationType());
        data.setValue("FANAM", family.getMemberName());
        log.info("FANAM姓名={}", family.getMemberName());
        data.setValue("TELNR", family.getMemberPhone());
        log.info("TELNR电话={}", family.getMemberPhone());
        data.setValue("STRAS", family.getMemberAddress());
        log.info("STRAS地址={}", family.getMemberAddress());
        data.setValue("FGBOT", family.getWorkPlace());
        log.info("FGBOT单位={}", family.getWorkPlace());
        data.setValue("FGBDT", "00000000");
        log.info("更新家庭成员SAP 入参完毕=====");

        func.execute(destination);
        JCoParameterList exportParameterList = func.getExportParameterList();
        log.info(exportParameterList.toXML());
        String type = exportParameterList.getStructure("RETURN").getString("TYPE");
        if ("S".equals(type)) {
            return true;
        }
        return false;
    }
}

